import api from '@/odoojs/index.js'

import { inject, watch, computed, reactive, ref, toRaw } from 'vue'

export function useTreeView(props) {
  const lang = inject('lang')

  const localState = {
    treeview: undefined
  }
  const state = reactive({
    pagination_changed: 0,
    metadata: {},
    records: [],
    sheet: {}
  })

  const activeIds = ref([])

  function view_get() {
    // check_lang()
    return localState.treeview
  }

  const buttons = computed(() => {
    const view = view_get(state.pagination_changed)
    if (view) {
      return view.buttons
    } else {
      return {}
    }
  })

  function fields2cols(fields) {
    const cols = Object.keys(fields).map(fld => {
      const info = fields[fld] || {}
      //   console.log(fld, info)
      return {
        dataIndex: info.name,
        key: fld,
        title: info.string,
        ...info,
        sorter: 'sorter' in info ? info.sorter : true

        //   ellipsis: 'ellipsis' in meta ? meta.ellipsis : false,
        //   width: meta.web_col_width,
      }
    })

    return cols
  }

  const columns = computed(() => {
    // console.log(state.sheet)
    // const view = view_get()
    // if (!view) return []

    // const sheet = view.view_sheet()
    // const flds = sheet.children
    const cols91 = fields2cols(state.sheet)
    // console.log(state.sheet)
    // console.log(cols91)

    const cols92 = cols91.filter(item => item.optional !== 'hide')

    const cols = cols92.filter(item => item.tagname === 'odoofield')

    return cols
  })

  const pagination = computed(() => {
    const view = view_get(state.pagination_changed)
    if (view) {
      return {
        total: view.length,
        pageSize: view.limit,
        current: view.current_page
      }
    } else {
      return {}
    }
  })

  // watch lang actionId
  watch(
    () => [lang.value, props.actionId],
    async (newVal, oldVal) => {
      // console.log('watch lang actionId', newVal, oldVal)
      if (newVal) {
        const [lang, actionId] = newVal
        if (lang && actionId) {
          load_action(actionId)
        }
      }
    },
    { immediate: true }
  )

  async function load_action(action_id) {
    console.log('load_action', action_id, lang.value)
    const act = api.action(action_id)
    // console.log(act)

    state.metadata = await act.load_metadata({
      callback: res => {
        state.metadata = res
        // console.log(datastore)
      }
    })
    // console.log('load_metadata ', state.metadata)

    const treeview = act.tree
    localState.treeview = treeview

    state.sheet = treeview.get_arch_sheet()
    // console.log('treeview sheet', state.sheet)

    // const sheet = state.sheet

    state.records = await treeview.load_data()
    state.pagination_changed += 1
  }

  const onSelectChange = keys => {
    console.log('selectedRowKeys changed: ', keys)
    activeIds.value = keys
  }

  async function onTableChange(vals) {
    // console.log(vals)
    const view = view_get()
    if (!view) return

    // const { current, pageSize, order } = vals

    // view.limit = pageSize
    // view.current_page = current
    // view.order = order

    // console.log(view)

    state.records = await view.load_data(vals)
    state.pagination_changed += 1
  }

  const records = computed(() => state.records)

  const treeInfo = computed(() => {
    const view = view_get()
    if (!view) return {}
    const info = {
      model: view.model,
      metadata: toRaw(state.metadata)
    }

    return { ...info }
  })

  return {
    treeInfo,
    buttons,
    records,
    columns,
    pagination,

    onTableChange,
    activeIds,
    onSelectChange
  }
}
